package com.rzico.sbl.ui.statistic

import android.view.View
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivitySendRecordBinding
import com.rzico.sbl.model.FilterData
import com.rzico.sbl.model.OrderData
import com.rzico.sbl.other.*
import com.rzico.sbl.ui.order.DeliverDetailActivity
import com.rzico.sbl.ui.order.OrderDetailActivity
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.phoneReplaceWithStar
import com.xinnuo.common.view.NestRadioGroup
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.helper.intValue
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class SendRecordActivity : BaseActivity(R.layout.activity_send_record) {

    private val mBinding by lazy { ActivitySendRecordBinding.bind(getRootView()) }

    override fun getViewModel() = get<StatisticCommonViewModel>()

    // 付款方式
    private val mPayList = arrayListOf(FilterData(name = "全部", hint = "报单收款"))

    // 线上订单
    private val mLineList = arrayListOf(
        FilterData(name = "全部", id = "", hint = "线上订单"),
        FilterData(name = "线上支付", id = "online", hint = "线上支付"),
        FilterData(name = "货到付款", id = "offline", hint = "货到付款"),
        FilterData(name = "电子水票", id = "eleTicket", hint = "电子水票"),
    )

    private lateinit var mDateMode: String
    private lateinit var mBeginDate: String
    private lateinit var mEndDate: String

    private var mOrderMethod = ""
    private var mPayMethod = ""

    override fun initData() {
        initTitle(title = "送货记录")

        initLayout()

        mBinding.rbSend1.performClick()
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关送货记录！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<OrderData>(R.layout.item_send_record) { jector, bean, _ ->
                        jector.apply {
                            text(
                                R.id.item_send_name,
                                "${bean.consignee}  ${
                                    when {
                                        userRole in "1,2"
                                                || privacyStatus == "off" -> bean.phone

                                        else -> bean.phone.phoneReplaceWithStar()
                                    }
                                }"
                            )
                            text(
                                R.id.item_send_type,
                                when (bean.methodDescr) {
                                    "offline" ->
                                        conditionIf(
                                            bean.payMethod.isNullOrEmpty(),
                                            "报单-电子水票",
                                            "报单-${bean.payMethod}"
                                        )

                                    else ->
                                        conditionIf(
                                            bean.payMethod.isNullOrEmpty(),
                                            "线上支付",
                                            "货到付款"
                                        )
                                }
                            )
                            text(R.id.item_send_code, bean.orderSn)
                            text(R.id.item_send_time, bean.createDate.getTimeString())
                            text(R.id.item_send_num, "${bean.quantity} 件")
                            text(R.id.item_send_pay, bean.amount.formatDecimal())
                            text(R.id.item_send_paper, bean.paperPaid.orEmpty("0"))
                            text(R.id.item_send_amount, bean.amountPaid.formatDecimal())

                            getView<View>(R.id.item_send_paper_ll)
                                .isVisible = bean.paperPaid.intValue > 0

                            clicked {
                                when (userRole) {
                                    in "1,2" ->
                                        startActivityEx<OrderDetailActivity>(
                                            "orderSn" to bean.orderSn,
                                            "shippingSn" to bean.sn
                                        )

                                    else -> startActivityEx<DeliverDetailActivity>(
                                        "orderSn" to bean.orderSn,
                                        "shippingSn" to bean.sn
                                    )
                                }
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    override fun initListener() {
        mDateMode = intent.getExtra("dateMode")
        mBeginDate = intent.getExtra("beginDate")
        mEndDate = intent.getExtra("endDate")

        // 今日、昨日、本周、本月、上月、本年、自定义
        mBinding.apply {
            when (mDateMode) {
                "2" -> {
                    sendTime.timeHint.text = "昨日"
                    getViewModel().mUncheckTimeList[1].isChecked = true
                }

                "3" -> {
                    sendTime.timeHint.text = "本周"
                    getViewModel().mUncheckTimeList[2].isChecked = true
                }

                "4" -> {
                    sendTime.timeHint.text = "本月"
                    getViewModel().mUncheckTimeList[3].isChecked = true
                }

                "5" -> {
                    sendTime.timeHint.text = "上月"
                    getViewModel().mUncheckTimeList[4].isChecked = true
                }

                "6" -> {
                    sendTime.timeHint.text = "本年"
                    getViewModel().mUncheckTimeList[5].isChecked = true
                }

                "7" -> {
                    sendTime.timeHint.text = "$mBeginDate ~ $mEndDate"
                    getViewModel().mUncheckTimeList[6].isChecked = true
                }

                else -> {
                    mBeginDate = getTodayDate()
                    mEndDate = getTodayDate()

                    sendTime.timeHint.text = "今日"
                    getViewModel().mUncheckTimeList[0].isChecked = true
                }
            }
        }

        mBinding.apply {
            sendTime.apply {
                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }

                                "2" -> {
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }

                                "3" -> {
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }

                                "4" -> {
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }

                                "5" -> {
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }

                                "6" -> {
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }

                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }

            rgSend.setOnCheckedChangeListener(
                object : NestRadioGroup.OnCheckedChangeListener {
                    override fun onCheckedChanged(group: NestRadioGroup, checkedId: Int) {
                        when (checkedId) {
                            R.id.rb_send1 -> {
                                mOrderMethod = ""
                                mPayMethod = ""

                                mLineList.forEach { it.isChecked = false }
                                rbSend2.text = "线上订单"
                                rbSend2Arrow.setImageResource(R.mipmap.icon_member01)

                                mPayList.forEach { it.isChecked = false }
                                rbSend3.text = "报单收款"
                                rbSend3Arrow.setImageResource(R.mipmap.icon_member01)

                                updateList()
                            }
                        }
                    }
                }
            )

            sendOnline.oneClick {
                getViewModel()
                    .showDropFilter(
                        context = getIContext(),
                        hintTV = mBinding.rbSend2,
                        anchor = mBinding.rbSend2Arrow,
                        bottom = mBinding.rgSend,
                        list = mLineList
                    ) { item ->
                        mBinding.rbSend2.performClick()
                        mBinding.rbSend2Arrow.setImageResource(R.mipmap.icon_member02)

                        mPayList.forEach { it.isChecked = false }
                        rbSend3.text = "报单收款"
                        rbSend3Arrow.setImageResource(R.mipmap.icon_member01)

                        mOrderMethod = conditionIf(item.id == "eleTicket", "", "online")
                        mPayMethod = item.id

                        updateList()
                    }
            }

            sendManual.oneClick {
                if (mPayList.size > 1) showActionFilter()
                else getViewModel().getPayment()
            }
        }

        getViewModel()
            .mPayEvent
            .observe(this) { list ->
                list.mapTo(mPayList) {
                    FilterData(
                        name = it.name.orEmpty(),
                        id = it.id,
                        hint = it.name.orEmpty()
                    )
                }

                mPayList.add(
                    FilterData(name = "其他", id = "other", hint = "其他")
                )

                showActionFilter()
            }
    }

    /**
     * 付款方式下拉框
     */
    private fun showActionFilter() {
        getViewModel()
            .showDropFilter(
                context = getIContext(),
                hintTV = mBinding.rbSend3,
                anchor = mBinding.rbSend3Arrow,
                bottom = mBinding.rgSend,
                list = mPayList
            ) { item ->
                mBinding.rbSend3.performClick()
                mBinding.rbSend3Arrow.setImageResource(R.mipmap.icon_member02)

                mOrderMethod = "offline"
                mPayMethod = item.id

                mLineList.forEach { it.isChecked = false }
                mBinding.rbSend2.text = "线上订单"
                mBinding.rbSend2Arrow.setImageResource(R.mipmap.icon_member01)

                updateList()
            }
    }

    /**
     * 送货订单记录列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .shipDetail(
                page = index,
                adminId = intent.getExtra("adminId"),
                orderMethod = mOrderMethod,
                payMethod = mPayMethod,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        (index == 0).condition {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}